$(document).ready(function(){
	$(window).on("load",function(){
		// 图片定位初始化
		imgLocation();

		// 渲染数据
		var dataImg = {"data":[
		   {"src":"../images/meitu1.png","text":"唯美意境美女图片","html":"美女"},
		   {"src":"../images/meitu2.jpeg","text":"诠释经典柔美","html":"发型"},
		   {"src":"../images/meitu4.jpeg","text":"超仙气波波发发型","html":"发型"},
		   {"src":"../images/meitu7.jpeg","text":"超仙气波波发发型","html":"发型"},
		   {"src":"../images/meitu9.jpeg","text":"诠释经典柔美","html":"发型"},
		   {"src":"../images/meitu11.jpg","text":"欧美男神qq头像","html":"头像"},
		   {"src":"../images/meitu12.jpg","text":"欧美男神qq头像","html":"头像"},
		   {"src":"../images/meitu14.jpg","text":"欧美气质女神图片高清手机壁纸","html":"壁纸"},
		   {"src":"../images/meitu15.png","text":"唯美意境美女图片","html":"美女"},
		   {"src":"../images/meitu16.jpeg","text":"唯美意境美女图片","html":"美女"},
		   {"src":"../images/meitu17.jpeg","text":"唯美意境美女图片","html":"美女"},
		   {"src":"../images/meitu18.jpeg","text":"诠释经典柔美","html":"发型"},
		   {"src":"../images/meitu20.jpeg","text":"唯美意境美女图片","html":"美女"}]
		}
		window.onscroll=function(){
			if(scrollside()){
				// 遍历数据，添加新的dom结构到container中
				$.each(dataImg.data,function(index,value){
					var box = $("<div>").addClass("box").appendTo($("#container"));// 加添box到container中
					var content = $("<div>").addClass("content").appendTo(box);// 添加content到box中
					$("<img>").attr("src","./img/"+$(value).attr("src")).appendTo(content);// 添加img到content中
					$("<h4>").text(value["text"]).appendTo(content);// 添加h4到content中
					$("<p>").html("<strong>标签：</strong>"+value["html"]).appendTo(content);// 添加p到content中
				});
				// 再次定位图片
				imgLocation();
			}
		}
		// 窗口大小发生变化图片重新定位
		window.onresize=function(){
			imgLocation();
		}
	});
});

// 判断是否滑动到出发事件的位置
function scrollside(){
	var windowHeight = $(window).height();
	var documentHeight = $(document).height();
	var scrollHeight = $(window).scrollTop();
	return windowHeight + scrollHeight + 100 >= documentHeight;
}

// 对图片进行定位
function imgLocation(){
	var box = $(".box");
	// 获取单个box的宽度
	var boxWidth = box.eq(0).width();
	// 获取当前的列数
	var num = Math.floor($(window).width()/boxWidth);
	// 定义高度队列
	var boxArr = [];
	box.each(function(index,value){
		//获取每个图片的高度
		var boxHeight = box.eq(index).height();
		// 第一行元素
		if(index<num){
			boxArr[index] = boxHeight;
			// 对第一行元素进行定位
			$(value).css({
				"position":"absolute",
				"top":0,
				"left":(boxWidth+20)*index
			});
		}else{
			// 找出最短列
			var minboxHeight = Math.min.apply(null,boxArr);
			var minboxIndex = $.inArray(minboxHeight,boxArr);

			$(value).css({
				"position":"absolute",
				"top":minboxHeight+20+"px",
				"left":box.eq(minboxIndex).position().left
			});
			// 更新最短高度
			boxArr[minboxIndex]+=box.eq(index).height()+20;
		}
	});
}